package com.liuguang.rabbitmq.controller;

import com.alibaba.fastjson.JSON;
import com.liuguang.api.rabbitmq.RabbitMqService;
import com.liuguang.api.redis.RedisService;
import com.liuguang.common.constans.CommonConstans;
import com.liuguang.common.pojo.CommonResult;
import com.liuguang.common.pojo.MqData;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpConnectException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TestController
 * @Description：
 * @Author: wanghr
 * Date: 2:39 PM 2020/10/15
 * Version: 1.0
 */
@RestController
@RequestMapping("/api/rabbitmq")
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private RabbitMqService rabbitMqService;


    @RequestMapping("/test")
    public CommonResult sendMessage() {
        int a = 0;
//        for ( a = 0; a < 4; a++) {
        MqData mqData = new MqData();
        rabbitMqService.sendEmail(mqData);
        System.out.println("第" + a + "条消息发送成功");
//        }
        return CommonResult.success("发送邮件成功");
    }

    @RequestMapping("/test1")
    public CommonResult sendTestMessage() {
        int a = 1;
        for (a = 1; a <= 3; a++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String msg = "第" + a + "条消息";
            MqData mqData = new MqData();
            mqData.setMsg(msg);
            HashMap<String, Object> map = new HashMap<>();
            map.put("key1", "sss");
            mqData.setData(map);

            rabbitMqService.sendTestMessage(mqData);
//            System.out.println("第" + a + "条消息发送成功" + mqData);
        }
        return CommonResult.success("消息发送成功");
    }

    @RequestMapping("/test2")
    public CommonResult sendTestMessage1() {

        try {
            MqData mqData = new MqData();
            mqData.setMsg("第1条消息");
            HashMap<String, Object> map = new HashMap<>();
            map.put("key1", "sss");
            mqData.setData(map);
            rabbitMqService.sendTestMessage1(mqData);
        } catch (AmqpConnectException e) {
            //这是为了处理 没有confirm 的异常，可能rabbitmq 挂了， 消息根本就没发出去
            //todo: 直接将消息放到 sendFailMessageHolder 中，后序重新发送
        }
        return CommonResult.success("消息发送成功");
    }
}
